<?php
/**
 * 	Bushido
 *
 * @category   Bushido
 * @package    Bushido_Auth_Adapter
 * @copyright  Copyright (c) 2008-2009 Nathan Keyes
 * @author Nathan Keyes
 * @version    $Id: Ldap.php 7 2009-11-14 22:42:08Z nkeyes $
 */

/**
 * Implements two-stage LDAP authentication
 * 
 * @category   Bushido
 * @package    Bushido_Auth_Adapter
 * @copyright  Copyright (c) 2008-2009 Nathan Keyes
 */
class Bushido_Auth_Adapter_Ldap extends Zend_Auth_Adapter_Ldap
{
	/**
	 * Overrides inherited single stage authenticate and impliments two-stage authentication
	 * 
	 * Returns an instance of Zend_Auth_Result
	 * @return Zend_Auth_Result
	 */
	public function authenticate()
	{
		$ldap = new Bushido_Ldap($this->_options);
		try
		{
			$result = $ldap->search(Zend_Ldap_Filter::equals('uid', $this->_username), $this->_options['baseDn']);
			$acct = $result->toArray();
			$dn = $acct[0]['dn'];

			
			$auth = Zend_Auth::getInstance();
			
			$adapter = new Zend_Auth_Adapter_Ldap(array($this->_options), $dn, $this->_password);
			return $auth->authenticate($adapter);
		}
		
		catch(Zend_Ldap_Exception $zle)
		{
		
			 //////////
			 // LDAP based authentication is notoriously difficult to diagnose. Therefore
			 // we bend over backwards to capture and record every possible bit of
			 // information when something goes wrong.
			 /////////
			 
			 //throw $zle;
			$err = $zle->getCode();
			
			if ($err == Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT)
			{
				$code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
				$messages[0] = "Account not found: $this->_username";
			}
			else
			{
				$line = $zle->getLine();
				$code = Zend_Auth_Result::FAILURE;
				$messages[] = $zle->getFile() . "($line): " . $zle->getMessage();
				$messages[] = str_replace($this->_password, '*****', $zle->getTraceAsString());
				$messages[] = 'An unexpected failure occurred';
			}
			$messages[] = $zle->getMessage();
			return new Zend_Auth_Result($code, $this->_username, $messages);
		}
	}
}